package cn.zhy.user.service.impl;

import cn.zhy.basic.constants.VerifyCodeConstants;
import cn.zhy.basic.exception.BusinessException;
import cn.zhy.basic.util.MD5Utils;
import cn.zhy.basic.util.StrUtils;
import cn.zhy.user.domain.Logininfo;
import cn.zhy.user.domain.User;
import cn.zhy.user.dto.UserDto;
import cn.zhy.user.mapper.LogininfoMapper;
import cn.zhy.user.mapper.UserMapper;
import cn.zhy.user.service.IUserService;
import cn.zhy.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;



    @Override
    public void save(User user) {
        //1.处理密码和盐值
        //获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //获取加密之后的密码
        String md5Pwd = MD5Utils.encrypByMd5(user.getPassword()+salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        super.save(user);
        //将user转换成logininfo属性
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        logininfoMapper.save(logininfo);

    }

    @Override
    public void remove(Long id) {
        //获取登录信息id
        User user = userMapper.loadById(id);
        logininfoMapper.remove(user.getLogininfoId());

        super.remove(id);
    }


    @Override
    public void update(User user) {
        //1.处理密码和盐值
        //获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //获取加密之后的密码
        String md5Pwd = MD5Utils.encrypByMd5(user.getPassword()+salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        //用户user：createtime和logininfo_id不能修改
        //获取登录信息id
        Long oldLogininfoId = userMapper.loadById(user.getId()).getLogininfoId();
        //将user转换为logininfo属性
        Logininfo logininfo = user2Logininfo(user);
        logininfo.setId(oldLogininfoId);
        logininfoMapper.update(logininfo);

        super.update(user);


    }




    /**
     * 邮箱注册
     * @param userDto
     */
    @Override
    public void email(UserDto userDto) {
        String email = userDto.getEmail();
        String pwd = userDto.getPwd();
        String confirmPwd = userDto.getConfirmPwd();

        //判断空值
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(pwd) || StringUtils.isEmpty(confirmPwd)){
                throw new BusinessException("不能为空");
        }
        //判断密码是否一致
        if (pwd.equals(confirmPwd)){
            throw new BusinessException("两次密码输入不一致");
        }

        //5.判断邮箱是否已经注册过
        User userEmail = userMapper.loadByEmail(userDto.getEmail());
        if (userEmail != null) {
            throw new BusinessException("您已注册过，请返回登录界面直接登录！");
        }

        //添加 t_logininfo信息
        //6.保存logininof数据
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);
        //先保存logininof数据才能拿到Logininfo_id保存到user表中
        logininfoMapper.save(logininfo);
        user.setLogininfoId(logininfo.getId());

        //7.保存user数据
        userMapper.save(user);



    }

    /**
     * 手机注册
     * @param userDto
     */
    @Override
    public void phone(UserDto userDto) {
        String phone = userDto.getPhone();
        String phoneCode = userDto.getPhoneCode();
        String pwd = userDto.getPwd();
        String confirmPwd = userDto.getConfirmPwd();
        System.out.println("======111111111111111111111111111111111111111" +phone);
        //1.空值校验
        if(StringUtils.isEmpty(phone)
                || StringUtils.isEmpty(phoneCode)
                || StringUtils.isEmpty(pwd)
                || StringUtils.isEmpty(confirmPwd)){
            throw new BusinessException("请输入正确的数据!!!");
        }

        //1.2.两次密码是否相同
        if(!pwd.equals(confirmPwd)){
            throw new BusinessException("两次密码不一致!!!");
        }

        //校验验证码是否过期 -  phone是key  根据key获取value ->code (9527 : 14725864666)
        Object objPhone = redisTemplate.opsForValue().get(VerifyCodeConstants.REGISTER_CODE_PREFIX + phone);
        System.out.println("================================================" +phone);
        if (objPhone == null){
            throw  new BusinessException("验证码无效，请重新获取!!!");
        }

        //校验验证码是否正确
        String codeTmp = objPhone.toString().split(":")[0];
        if (!codeTmp.equalsIgnoreCase(phoneCode)){
            throw new BusinessException("验证码错误!!!");
        }
        //保存数据-先保存到t_logininfo
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.save(logininfo);//自增
        //保存user-先获取logininfo的id设置进去在添加到user
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);
    }


    /**
     * 将user的值同步赋值给logininfo
     * @param user
     * @return
     */
    private Logininfo user2Logininfo(User user) {
        //创建一个logininfo对象
        Logininfo logininfo = new Logininfo();
        //调用工具类：按照同名属性赋值 - 将user的值赋值给logininfo
        BeanUtils.copyProperties(user, logininfo);
        //设置type类型为1：表示用户
        logininfo.setType(1);

        return logininfo;
    }

    /**
     * 将UserDto对象的数据同步到User对象中
     * @param userDto
     * @return
     */
    private User userDto2User(UserDto userDto) {
        //创建一个user对象
        User user = new User();
        /**
         * 将userDto现有的值赋值给user
         */
        //用户名就是手机号
        user.setUsername(userDto.getPhone());
        //手机号
        user.setPhone(userDto.getPhone());
        //密码 - 保存到数据库需要加盐加密
        //获取32位随机的盐值
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        //调用工具类加盐加密再保存到对象中
        user.setPassword(MD5Utils.encrypByMd5(salt + userDto.getPwd()));

        return user;
    }


}
